import { DynamicIndex } from "./types/commonTypes";
import axios, {
  Axios,
  AxiosError,
  AxiosRequestConfig,
  AxiosResponse,
} from "axios";

// application/x-www-form-urlencoded、multipart/form-data
const commonHeaders = {
  "Access-Control-Allow-Origin": "*",
  "Content-Type": "application/json;charset=UTF-8",
  "X-Requested-With": "XMLHttpRequest",
};

let reqNum: number = 0;

const setLoading = (): void => {
  if (!reqNum) {
    // 加载动画 loading
  }
  reqNum++;
};

const clearLoading = (): void => {
  if (reqNum > 0) {
    reqNum--;
  }
  if (reqNum === 0) {
    // 清除加载动画 clear loading
  }
};

const useUrl =
  process.env.NODE_ENV === "development" ? "" : "正式地址 official address";

const typeReg: RegExp = new RegExp("application/x-www-form-urlencoded+");

const request: Axios = axios.create({
  url: useUrl,
  headers: commonHeaders,
  timeout: 30000,
});

request.interceptors.request.use(
  (config: AxiosRequestConfig<any>) => {
    setLoading();
    if (
      config.method?.toUpperCase() === "POST" &&
      typeReg.test(
        !!config && !!config.headers && (config?.headers["Content-Type"] as any)
      )
    ) {
      config.data = qs.stringify(config.data);
    }
    return config;
  },
  (error: AxiosError) => {
    clearLoading();
    Promise.reject(error);
  }
);

request.interceptors.response.use(
  (res: AxiosResponse | any) => {
    if (res.code === 200) {
      setLoading();
      return Promise.resolve(res.data);
    }
    Promise.reject(res);
  },
  (error: AxiosError) => {
    clearLoading();
    Promise.reject(error);
  }
);

interface OptionProps {
  headers?: any;
  method?: string;
  data?: DynamicIndex;
  timeout?: number;
}

export default request;

export const post = (url: string, data: DynamicIndex): Promise<void> =>
  request.post(url, data);

export const get = (url: string, data: DynamicIndex): Promise<void> =>
  request.get(url, data);

// 上传文件 upload
export const upload = (data: DynamicIndex) => {
  const url: string = "";
  let params: FormData = new FormData();
  for (const key in data) {
    if (Object.prototype.hasOwnProperty.call(data, key)) {
      const value = data[key];
      params.append(key, value);
    }
  }
  return request.post(url, data, {
    headers: { "Content-Type": "multipart/form-data;charset=UTF-8" },
  });
};

// 数据格式化 data formatting
export class qs {
  static stringify(data: DynamicIndex): string {
    let res: string = "";
    for (const key in data) {
      if (Object.prototype.hasOwnProperty.call(data, key)) {
        const value = data[key];
        res += `${key}=${value}&`;
      }
    }
    return res.substring(0, res.length - 1);
  }
  static parse(data: string): Object {
    const res: DynamicIndex = {};
    const dataArr: string[] = data.split("&");
    for (let i = 0, len = dataArr.length; i < len; i++) {
      const item: string = dataArr[i];
      const key: string = item.split("=")[0];
      const value: string = item.split("=")[1];
      res[key] = value;
    }
    return res;
  }
}
